package com.xuecheng.content.controller;

import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.BindTeachplanMediaDto;
import com.xuecheng.commons.model.dto.TeachplanDto;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.web.exceptions.BusinessException;
import org.simpleframework.xml.Path;
import org.springframework.web.bind.annotation.*;
import com.xuecheng.content.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>
 * 课程计划前端控制器
 * </p>
 *
 * @author 七安
 */
@Slf4j
@RestController
@RequestMapping("/teachplan")
public class TeachplanController {

    @Autowired
    private TeachplanService teachplanService;

    /**
     * 根据课程id查询课程计划。（包括1，2，3级结构）
     *
     * @param courseId 课程id
     * @return 查到的结果
     */
    @GetMapping("/{courseId}/tree-nodes")
    public ResponseResult<TeachplanVo> findTeachplanByCourseId(@PathVariable("courseId") Long courseId) {
        return ResponseResult.okResult(teachplanService.findTeachplanByCourseId(courseId));
    }

    /**
     * 保存或更新课程计划
     *
     * @param teachplanDto 要存的内容
     * @return 响应对象
     */
    @PostMapping()
    public ResponseResult saveOrUpdatePlan(@RequestBody TeachplanDto teachplanDto) throws BusinessException {
        //调用Service处理
        teachplanService.saveOrUpdatePlan(teachplanDto);
        return ResponseResult.okResult();
    }

    /**
     * 根据id删除章节
     *
     * @param id 要删除的id
     * @return 结果
     */
    @DeleteMapping("/{id}")
    public ResponseResult deletePlanById(@PathVariable Long id) throws BusinessException {
        teachplanService.deletePlanById(id);
        return ResponseResult.okResult();
    }

    /**
     * 课程绑定媒资
     *
     * @param bindTeachplanMediaDto 接收
     * @return 结果
     */
    @PostMapping("/media/association")
    public ResponseResult mediaBindingTeachplan(@RequestBody BindTeachplanMediaDto bindTeachplanMediaDto) throws BusinessException {
        return teachplanService.mediaBindingTeachplan(bindTeachplanMediaDto);
    }

    /**
     * 删除媒资绑定
     *
     * @param teachPlanMediaId 媒资id
     * @param courseBaseId     课程id
     * @return 结果
     */
    @DeleteMapping("/media/{teachPlanMediaId}")
    public ResponseResult deleteMediaBinding(@PathVariable("teachPlanMediaId") Long teachPlanMediaId, Long courseBaseId) throws BusinessException {
        //调用service
        return teachplanService.deleteMediaBinding(teachPlanMediaId, courseBaseId);
    }

    @GetMapping("/{teachplanId}")
    public ResponseResult<TeachplanVo> findTeachplanById(@PathVariable("teachplanId") Long teachplanId) throws BusinessException {
        //判空
        if (teachplanId == null) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        return ResponseResult.okResult(teachplanService.getById(teachplanId));
    }
}
